<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 订单状态管理
 * @author zxj
 *
 */
class Order_parts extends MY_Controller {
	private $t_pParts = 'mt_product_parts';
	function __construct() {
		parent::__construct();
	}


    function serviceCurrency(){
        echo currency_service('USD','EUR','226.99');
    }


    /**
     * 导出配件
     */
    function exportParts(){
        $sql = "select pj.id,pj.pid,pj.oid,pj.sku,pj.name,pj.quantity,pj.price,pj.rate_price,pj.rate_currency,pj.point,pj.status,
            cp.status_id,cp.add_time,cp.fault,cp.repairItem,
            ps.name_ch,ps.name_en,
            dd.order_num,dd.create_time,FROM_UNIXTIME(cp.add_time,'%Y-%m-%d %H:%i:%s') as update_date
            from mt_product_parts as pj
            left join mt_product as cp on pj.pid = cp.id
            left join mt_product_status as ps on cp.status_id = ps.id
            left join mt_order as dd on cp.oid = dd.id
            where cp.brandCustomerNum = 24";
        $dataList = $this->common_model->getQuery($sql,'result_array');
        $fieldData = array(
            'id'=>'配件ID','pid'=>'产品ID','order_num'=>'维修单号','sku'=>'sku','name'=>'配件名称',
            'quantity'=>'配件数量','rate_price'=>'配件站点报价','rate_currency'=>'配件货币',
            'point'=>'站点简称','name_ch'=>'产品状态','create_time'=>'订单创建日期','update_date'=>'产品更新日期',
        );
        $title = date('y-m-d').$this->users['account'];
        $sheetTitle = date('Ymd');
        excel_output($title,$fieldData,$dataList,$sheetTitle);
    }



	/**
	 * 列表页
	 */
	function index()
    {
        //获取表单数据
        $data = $formField = gp();
        //查询条件
        $where = $whereLike = array();
        //默认select设置
        $keyword = trim($data['keyword']);
        $searchStr = 'orders/Order_parts/index/?';
        if($keyword){
            if(strpos($keyword,'-') && strlen($keyword)==13){
                $where['sku'] = $keyword;
            }elseif(strpos($keyword,'wx')===0 && strlen($keyword)==16){
                $where['order_num'] = $keyword;
            }else{
                if (preg_match('/[\x7f-\xff]/', $keyword)) {
                    $whereLike['name_ch'] = $keyword;
                }else{
                    $whereLike['name_en'] = $keyword;
                }
            }
            $searchStr .= 'keyword='.$keyword;
        }
        //状态
        $status = intval($data['status']);
        if ($status) {
            $where['status'] = $status;
            $searchStr .= '&status=' . $status;
        }
        //默认select设置
        $optStatus[$status] = 'selected';
        $data['optStatus'] = $optStatus;
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->common_model->countRows($this->t_pParts, $where, '', $whereLike);
        $config['per_page'] = $data['outputExcel'] ? $config['total_rows'] : 20;
        $page = max(1, intval($data['page']));
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $dataList = $this->common_model->select($this->t_pParts, $slimit, $config['per_page'], 'id desc', $where, '', $whereLike);
        $data['show_pages'] = $this->pagination->create_links();
        //重构数据
        $statusAry = array(
            'ch'=>array(1=>'正常',2=>'待处理',3=>'待采购'),
            'en'=>array(1=>'Normal',2=>'pending',3=>'wait purchase')
        );
        foreach ($dataList as &$rs) {
            $rs['nameSub'] = mb_substr($rs['name'], 0, 20) . '...';
            $pid = intval($rs['pid']);
            $rs['add_time'] = date('Y-m-d H:i:s',$rs['add_time']);
            $sql = 'select a.name_ch,a.name_en from mt_product_status as a
                    left join mt_product as b on a.id = b.status_id
                    where b.id=\''.$pid.'\'';
            $products = $this->common_model->getQuery($sql,'row_array');
            $rs['pStatusName'] = $products['name_'.$this->curLang];
            $statusID = $rs['status'];
            $rs['statusName'] = $statusAry[$this->curLang][$statusID];
            $rs['price'] = $rs['price'] . ' ' . $rs['currency'];
            $rs['rate_price'] = $rs['rate_price'] . ' ' . $rs['rate_currency'];
            $rs['isSupplementName'] = $rs['isSupplement']?"Y":'N';
        }
        unset($rs);
        $data['dataList'] = $dataList;
        //导出数据
        $data['outputUrl'] = blang_url($searchStr . '&outputExcel=true');
        if ($data['outputExcel']) {
            $fieldData = array(
                'id'=>'ID','pid'=>'产品ID','order_num'=>'维修编号',
                'sku'=>'SKU','name'=>'配件名称','quantity'=>'数量','pStatusName'=>'维修状态',
                'rate_price'=>'售价','rate_currency'=>'货币','cost_price'=>'成本价','add_time'=>'添加日期',
                'add_user'=>'添加人','point'=>'站点标识','statusName'=>'状态'
            );
            excel_output(date('y-m-d'), $fieldData, $dataList);
        } else {
            //视图以及样式
            $this->load->view('defaults/order_parts_list', $data);
            $this->load->view('defaults/common/footer');
        }
    }


    /**
     * 删除状态
     * @param string $id
     * @param string $page
     */
    function del($id = '',$page = ''){
        if($this->users['account'] != 'zlj')
            show_error('管理员的权限');
        $id = intval($id);
        $where = array('id'=>$id);
        $this->common_model->delete($this->t_pParts,$where);
        $this->common_model->delete($this->t_pParts,array('id'=>$id));
        redirect(blang_url('orders/Order_parts/index/?page='.intval($page)));
    }

    /**
     * 人工生成采购单
     */
    function artificialCreatePartsNeed()
    {
        $gp = gp();
        $result = $this->common_model->createPartsNeed($gp['id']);
        if ($result['success']) {
            $this->common_model->update('mt_product_parts' , array('is_sync' => 1) , array('id' => $gp['id']));
            //redirect(blang_url('orders/Order_parts/index/?page='.intval(0)));
            echo(json_encode(array("status" => '1' , 'msg' => "提交成功！")));
            exit;
        }
        else {
            echo(json_encode(array("status" => '0' , 'msg' => $result['message'])));
            exit;

        }
    }

    /**
     * 人工取消采购
     */
    function cancelPurchase(){
        $gp=gp();
        if(ENVIRONMENT == 'development'){
            $url = 'http://47.90.55.9:8889/webService/cancelAccessoryPurchaseNewOrder.php';
        }else{
            $url = 'http://stock.dhhtgroup.com/webService/cancelAccessoryPurchaseNewOrder.php';
        }
        $data = array(
            'account'=>'tomrepair',
            'token'=>'tomrepairAccessoryPurshase',
            'data'=>json_encode(array($gp['id']))
        );
        $result=CurlPost($url,$data);
        if($result['success']){
            $this->common_model->update('mt_product_parts',array('sap_status'=>4),array('id'=>$gp['id']));
            redirect(blang_url('orders/Order_parts/index/?keyword='.$gp['keyword']));
            die("1");
        }else{

            die("0");

        }
    }
}
